package com.kemorebi.forum.controller;

import com.kemorebi.forum.common.BaseController;
import com.kemorebi.forum.common.R;
import com.kemorebi.forum.config.OssConfig;
import com.kemorebi.forum.utils.PathUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@RestController
@RequestMapping("/upload")
public class UploadFile extends BaseController {
    @Resource
    private OssConfig ossConfig;
    @PostMapping("/coverImg")
    @ApiOperation("上传文章背景")
    public R<String> coverImg(@RequestParam("img") MultipartFile img){
        String originalFilename = img.getOriginalFilename();
        if (originalFilename == null || "".equals(originalFilename)) {
            fail("不能为空");
        }
        //正则表达式判断文件类型
        if (!originalFilename.toLowerCase().matches(".*\\.(jpg|png|gif|jpeg)$")) {
            fail("文件类型不符合！");
        }
        //如果判断通过上传文件到OSS
        String filePath ="img/" +PathUtils.generateFilePath(originalFilename);
        return  success( ossConfig.upload(img,filePath));
    }

}
